package com.baidu.logindemos.db.model

import android.content.Context
import android.content.SharedPreferences

/**
 * SharedPreferences 工具类
 * saveUser
 * getUser
 */
class SharedPreferencesUtil private constructor(){
    private lateinit var sp: SharedPreferences

    companion object{
        val instance: SharedPreferencesUtil by lazy { SharedPreferencesUtil() }
        val SP_NAME = "login_demo"
        val NAME_KEY = "name"
        val PASSWORD_KEY = "password"
    }

    /**
     * 必须先调用init方法
     */
    fun init(context: Context) {
        sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
    }

    /**
     * 保存用户信息
     */
    fun saveUser(user: UserModel){
        sp.edit().also {
            it.putString(NAME_KEY, user.name)
            it.putString(PASSWORD_KEY, user.password)
            it.commit()
        }
    }

    /**
     * 获取用户信息
     */
    fun findUser(name:String):UserModel?{
        val nameValue = sp.getString(NAME_KEY, "")
        if (name == nameValue){
            val passwordValue = sp.getString(PASSWORD_KEY,"")!!
            return UserModel(nameValue, passwordValue)
        }else{
            return null
        }
    }

}